#!/usr/bin/env python

# This file contains objects related to Graph.  
from scipy import *
import numpy

class Graph(object):
	def __init__(self, m = 10):
		print 'Initialzing Graph...'
		self.AdjMatrix = zeros( (m, m) )
		
	
	def __del__(self):
		print 'Deleting Graph...'

	def AddLink(self, i, j):
		i -= 1
		j -= 1
		if self.AdjMatrix[i, j] != 0:
			print '[WARNING] Link (' + str(i) + ', ' + str(j) + ') exists already!!'
		else:
			self.AdjMatrix[i, j] = 1
	
	def DelLink(self, i, j):
		i -= 1
		j -= 1
		if self.AdjMatrix[i, j] == 0:
			print '[WARNING] Link (' + str(i) + ', ' + str(j) + ') doesnot exist!!'	
		else:
			self.AdjMatrix[i, j] = 0
	
	# Check whether there is link between i and j. 
	def IsLink(self, i, j):
		i -= 1
		j -= 1
		return self.AdjMatrix[i, j]
	
	def Len(self):
		return self.AdjMatrix.shape[0]

	
	def Multiply(self, M):
		M = asarray(M)
		# return multiply(self.AdjMatrix, M)
		return self.AdjMatrix * M

	
	def Shape(self):
		return self.AdjMatrix.shape

	
	def Print(self):
		print self.AdjMatrix

	def WriteDownAdjMat(self, fileName):
		'''Write the Adjacent Matrix to a text file'''
		f = open(fileName, "w")
		M = len(self.AdjMatrix)
		f.write(str(M)+'\n')
		for i in range(M):
			string = ''
			for j in range(M):
				string += str( int(self.AdjMatrix[i, j] ) )
				string += ' '
			string += '\n'
			f.writelines(string)

		f.close()

	def GetLinkNum(self):
		'''Get how many links this graph has'''
		num = 0
		M = len(self.AdjMatrix)
		for i in range(M):
			for j in range(M):
				if self.AdjMatrix[i, j]:
					num += 1
		return num


	def __str__(self):
		return str(self.AdjMatrix)



if __name__ == "__main__":
	print '123...'
	g = Graph(5)
	g.Print()
	g.AddLink(3, 5)
	g.Print()
	print g.Len()
	x = g.Multiply(mat(zeros( (5, 5) )))
	# x = g.Multipy(zeros( (5, 5) ))
	print x
	print '-----'
	print g
	# g.WriteDownAdjMat('./test.txt')

			
